<?php
/*
 * cookie: 'PHPSESSID'
 *
 * server:
    ['DOCUMENT_ROOT'] =>        '/home/babagayr/public_html/remontik.kh.ua'
    ['GATEWAY_INTERFACE'] =>    'CGI/1.1'
    ['HTTP_ACCEPT'] =>          'text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8'
    ['HTTP_ACCEPT_ENCODING'] => 'gzip, deflate'
    ['HTTP_ACCEPT_LANGUAGE'] => 'en-US,en;q=0.5'
    ['HTTP_CONNECTION'] =>      'keep-alive'
    ['HTTP_COOKIE'] =>          'PHPSESSID=3a0622382513193024eb52a06c187c87'
    ['HTTP_HOST'] =>            'remontik.kh.ua'
    ['HTTP_USER_AGENT'] =>      'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0 FirePHP/0.7.4'
    ['HTTP_X_INSIGHT'] =>       'activate'
    ['PATH'] =>                 '/bin:/usr/bin'
    ['PHPRC'] =>                '/home/babagayr/'
    ['QUERY_STRING'] =>
    ['REDIRECT_STATUS'] =>      200
    ['REDIRECT_UNIQUE_ID'] =>   'Um5TNVvFgb4ACPROIQkAAAAJ'
    ['REDIRECT_URL'] =>         '/life'
    ['REMOTE_ADDR'] =>          178.32.52.246
    ['REMOTE_PORT'] =>          57438
    ['REQUEST_METHOD'] =>       'GET'
    ['REQUEST_URI'] =>          '/life'
    ['SCRIPT_FILENAME'] =>      '/home/babagayr/public_html/remontik.kh.ua/index.php'
    ['SCRIPT_NAME'] =>          '/index.php'
    ['SERVER_ADDR'] =>          91.197.129.190
    ['SERVER_ADMIN'] =>         'webmaster@remontik.babagay.ru'
    ['SERVER_NAME'] =>          'remontik.kh.ua'
    ['SERVER_PORT'] =>          80
    ['SERVER_PROTOCOL'] =>      'HTTP/1.0'
    ['SERVER_SIGNATURE'] =>
    ['SERVER_SOFTWARE'] =>      'Apache'
    ['UNIQUE_ID'] =>            'Um5TNVvFgb4ACPROIQkAAAAJ'
    ['PHP_SELF'] =>             '/index.php'
    ['REQUEST_TIME'] =>         1382961973
    ['argv'] =>
    ['argc'] =>

 */
/*
 * //fb(PUBLIC_URL); // http://remontik.kh.ua // http://127.0.0.1/zoqa
 * //fb(CURRENT_URL); //http://remontik.kh.ua
 *
 * TODO взять полный урл, убрать из него название сайта, потом разбить на массив
 *
 * TODO перенести сюда метод разбора get-аргументов типа /page/1/ => page=1
 */

final class Request {
    public $get = array();
    public $post = array();
    public $cookie = array();
    public $files = array();
    public $server = array();
    public $uri = array();

    public $get_params = array();

    public function __construct() {

        $_GET = $this->clean($_GET);
        $_POST = $this->clean($_POST);
        $_REQUEST = $this->clean($_REQUEST);
        $_COOKIE = $this->clean($_COOKIE);
        $_FILES = $this->clean($_FILES);
        $_SERVER = $this->clean($_SERVER);

        $this->get = $_GET;
        $this->post = $_POST;
        $this->request = $_REQUEST;
        $this->cookie = $_COOKIE;
        $this->files = $_FILES;
        $this->server = $_SERVER;

        $this->uri = $this->getURI();

        //Registry::getInstance() -> set("Request", $this);

        $this->setGetParamsArray();
    }

    function getParameter($name){
        if(isset($this->get[$name])) return $this->get[$name];
        if(isset($this->post[$name])) return $this->post[$name];
        if(isset($this->cookie[$name])) return $this->cookie[$name];
        if(isset($this->files[$name])) return $this->files[$name];
        if(isset($this->server[$name])) return $this->server[$name];
        if(isset($this->uri[$name])) return $this->uri[$name];
        if(isset($this->get_params[$name])) return $this->get_params[$name];

        return null;
    }

    function setGetParamsArray(){

        if(count($this->server['QUERY_STRING']) > 0){
            $s = explode('&', $this->server['QUERY_STRING']);
            foreach($s as $key => $value){
                $v = explode('=', $value);
                if(isset($v[0]) AND isset($v[1])){
                    $v[0] = preg_replace('/amp;/','',$v[0]);
                    $v[0] = preg_replace('/&/','',$v[0]);
                    $name = $v[0];
                    $val = $v[1];
                    $this->get_params[$name] = $val;
                }
            }
        }
    }

    /*
     * Взять параметр типа ?param=value
     */
    function getParam($name){

        if(isset($this->get_params[$name])) return $this->get_params[$name];

        return null;
    }

    /*
     * Взять пост-параметр
     */
    function postParam($name){
        if(isset($this->request[$name])) return $this->request[$name];

        return null;
    }

    public function clean($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                unset($data[$key]);

                $data[$this->clean($key)] = $this->clean($value);
            }
        } else {
            $data = htmlspecialchars($data, ENT_COMPAT);
        }

        return $data;
    }

    function selfURL(){
        if(!isset($_SERVER['REQUEST_URI']))    $suri = $_SERVER['PHP_SELF'];
        else $suri = $_SERVER['REQUEST_URI'];
        $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
        $sp=strtolower($_SERVER["SERVER_PROTOCOL"]);
        $pr =    substr($sp,0,strpos($sp,"/")).$s;
        $pt = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
        return $pr."://".$_SERVER['SERVER_NAME'].$pt.$suri;
    }


    function getURI(){
        $uri = null;

        $self_url = $this->selfURL();

        // $uri =  $this->clean($_SERVER['REQUEST_URI']);
        $uri =  $this->clean( str_replace(PUBLIC_URL,'',$self_url ));

        // отсечь гет-парматеры
        $get = explode('?',$uri);

        if(isset($get[1]))
            $uri = $get[0];

        #
        $uri = explode("/",$uri);

        $tmp[] = null;

        if(is_array($uri))
            foreach($uri as $k => $v){
                if( (bool)$v !== false ) $tmp[] = $v;
            }

        unset($tmp[0]);

        $uri = $tmp;

        unset($tmp);

        return $uri;
    }

    /*
     * returns@ string|array|null
     * [!] нумерация аргументов URI начинается с 1
     */
    function getURIarg( $index = null ){

        if(isset($index)){
            if(isset($this->uri[$index])){
                return Registry::getInstance()->Model->translitBackToCyr($this->uri[$index]);
            }
            return null;
        } else
            return $this->uri;
    }

        function get( $index = null ){
            return $this->getURIarg($index);
        }
}